<template>
  <div>
    <el-card>
      <template #header>
        <div class="searchHead">
          <el-form :model="form" inline>
            <el-form-item label="任务名称">
              <el-input
                v-model="form.jobName"
                class="w-50 m-2"
                placeholder="请输入任务名称"
                clearable
              >
                <template #prefix>
                  <el-icon class="el-input__icon"><search /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="任务状态">
              <el-select
                v-model="form.state"
                filterable
                clearable
                placeholder="请选择任务状态"
                style="width: 200px"
              >
                <el-option
                  v-for="item in options"
                  :key="item.enterpriseId"
                  :label="item.cmpName"
                  :value="item.enterpriseCode"
                />
                <template #prefix>
                  <el-icon class="el-input__icon"><search /></el-icon>
                </template>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="
                  dialogFormVisible = true;
                  isEdit = false;
                "
              >
                新增任务<el-icon class="el-input__icon"><Plus /></el-icon>
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <el-table
        ref="enterpriseRef"
        :data="tableData"
        style="width: 100%; max-height: 65vh"
        :row-class-name="tableRowClassName"
        table-layout="auto"
        v-loading="loading"
        :header-cell-style="{'text-align':'center'}"
        :cell-style="{'text-align':'center'}"
      >
        <el-table-column fixed prop="jobName" label="任务名称" />
        <el-table-column prop="name" label="错误策略" show-overflow-tooltip/>
        <el-table-column prop="cronExpression" label="cron执行表达式" />
        <el-table-column prop="jobClassName" label="调用目标方法" />
        <el-table-column prop="invokeParam" label="调用目标参数" />
        <el-table-column prop="triggerState" label="状态" />
        <el-table-column prop="description" label="任务描述" show-overflow-tooltip/>
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <div
              v-if="
                scope.row.triggerState != 'ACQUIRED' &&
                scope.row.triggerState != 'BLOCKED' &&
                scope.row.triggerState != 'WAITING'
              "
            >
              <el-button
                link
                type="primary"
                size="small"
                @click="resume(scope.$index, scope.row)"
                >恢复任务</el-button
              >
            </div>
            <!-- <div v-else>
              <el-button
                link
                type="primary"
                size="small"
                @click="stopNow(scope.$index, scope.row)"
                >停止任务</el-button
              >
            </div> -->
              <el-button
                link
                type="primary"
                size="small"
                @click="stopNow(scope.$index, scope.row)"
                >停止任务</el-button
              >

            <el-button
              link
              type="primary"
              size="small"
              @click="modify(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              link
              type="primary"
              size="small"
              @click="delJob(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        layout="prev, pager, next, sizes"
        v-model:page-size="pagination.size"
        v-model:current-page="pagination.page"
        :total="pagination.total"
        @size-change="sizeChange"
        @current-change="pageChange"
        class="pagination"
      />
      <!-- 新增任务对话框 -->
      <el-dialog
        v-model="dialogFormVisible"
        destroy-on-close
        :title="dialogTitel"
        style="padding-left: 20px; padding-right: 20px"
      >
        <el-form :model="form" label-width="100px">
          <el-form-item label="任务名称">
            <el-input v-model="form.jobName" />
          </el-form-item>
          <el-form-item label="任务分组">
            <el-input v-model="form.jobGroup" />
          </el-form-item>
          <el-form-item label="执行任务类名">
            <!-- <el-input v-model="form.jobClassName" /> -->
            <el-select
              v-model="form.jobClassName"
              filterable
              clearable
              placeholder="请选择任务"
            >
              <el-option
                v-for="item in jobOptions"
                :key="item.className"
                :label="item.label"
                :value="item.className"
              />
              <template #prefix>
                <el-icon class="el-input__icon"><search /></el-icon>
              </template>
            </el-select>
          </el-form-item>
          <el-form-item label="时间表达式">
            <el-popover
              placement="bottom"
              title="选择时间表达式"
              :width="900"
              trigger="click"
              content="this is content, this is content, this is content"
            >
              <template #reference>
                <el-input
                  @click="cronPopover = true"
                  v-model="form.cronExpression"
                  @change="cronChange()"
                />
              </template>
              <Vue3Cron
                @change="changeCron"
                v-model:value="form.cronExpression"
                style="width: 600px"
              />
              <div style="width: 300px"></div>
            </el-popover>
          </el-form-item>
          <el-form-item label="需要传递参数">
            <el-input v-model="form.invokeParam" />
          </el-form-item>
          <el-form-item label="任务状态">
            <el-input v-model="form.triggerState"/>
          </el-form-item>
          <el-form-item label="工作描述">
            <el-input v-model="form.description" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="add"> 确定 </el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import {
  addJob,
  queryjob,
  jobResume,
  jobPause,
  deleteJob,
  jobList,
  modifyJob,
} from "@/api/quartz";
import { ElMessage } from "element-plus";
import Vue3Cron from "@/components/vue3Cron/index.vue";
import cronParser from "cron-parser";

const dialogFormVisible = ref(false);
const loading = ref(true);
const options = ref([]);
const tableData = ref([]);
let isEdit = ref(false);
let dialogTitel = ref("新增任务");
const jobOptions = ref([]);
const cronPopover = ref(false);
const form = reactive({
  jobName: "", //工作名称
  jobGroup: "", //工作组
  jobClassName: "", //工作类
  cronExpression: "", //任务执行方式 cron表达式
  invokeParam: "", //传递参数
  description: "", //工作描述
});
let codeData = {
  ERROR: "错误",
  PAUSED: "暂停",
  ACQUIRED: "运行中",
};
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0,
});
const jobNameList = {}
const jobForm = reactive({});
//立马停止任务
const stopNow = (row, rowData) => {
  let data = {
    jobName: rowData.jobName,
    jobGroup: rowData.jobGroup,
  };
  jobPause(data)
    .then((res) => {
      //获取到信息
      ElMessage.success("暂停成功!");
      getList();
    })
    .catch((msg) => {
      //获取出错
      ElMessage.error("暂停失败,请联系管理员！");
    });
};
const resume = (row, rowData) => {
  let data = {
    jobName: rowData.jobName,
    jobGroup: rowData.jobGroup,
  };
  jobResume(data)
    .then((res) => {
      //获取到信息
      ElMessage.success("恢复成功!");
      getList();
      dialogFormVisible.value = false;
    })
    .catch((msg) => {
      //获取出错
      ElMessage.error("恢复失败,请联系管理员！");
    });
};
//编辑任务
const modify = (row, rowData) => {
  form.jobName = rowData.jobName; //工作名称
  form.jobGroup = rowData.jobGroup; //工作组
  form.jobClassName = rowData.jobClassName; //工作类
  form.cronExpression = rowData.cronExpression; //任务执行方式 cron表达式
  form.invokeParam = rowData.invokeParam; //传递参数
  form.description = rowData.description; //工作描述
  dialogFormVisible.value = true;
  dialogTitel.value = "修改任务";
  isEdit.value = true;
};
const edit = () => {
  modifyJob(form)
    .then((res) => {
      if (res == true) {
        getList();
        dialogFormVisible.value = false;
        ElMessage.success("修改成功！");
      }
    })
    .catch((msg) => {});
};
//删除任务
const delJob = (row, rowData) => {
  let params = {
    jobName: rowData.jobName,
    jobGroup: rowData.jobGroup,
  };
  deleteJob(params)
    .then((res) => {
      //获取到信息
      ElMessage.success("删除成功!");
      getList();
    })
    .catch((msg) => {
      //获取出错
      ElMessage.error("删除失败,请联系管理员！");
    });
};

const getList = () => {
  let data = {
    pageNum: pagination.page,
    pageSize: pagination.size,
  };

  queryjob(data)
    .then((res) => {
      //获取到信息
      tableData.value = reDataValue(res);
      loading.value = false;
    })
    .catch((msg) => {
      console.log(msg)
      //获取出错
      ElMessage.error("获取信息出错,请稍后再试！");
    });
  if (jobOptions.value.length > 0) {
    return;
  }
  jobList()
    .then((res) => {
      // jobOptions.value = res;
      
      let list =[]
      for(let key in res){
        let item = {className:key,label:res[key]}
        list.push(item)
      }
      console.log(res)
      jobOptions.value = list
      
    })
    .catch((msg) => {
      ElMessage.error("获取可执行任务信息失败,请刷新重试！");
      //获取出错
      console.log(msg);
    });
};
const add = () => {
  /* if (isEdit == false) {
   
  }
  edit(); */
  addJob(form)
      .then((res) => {
        if (res.status == 200) {
          ElMessage.success("添加成功！");
          dialogFormVisible.value = false;
          getList();
        } else {
          ElMessage.error("添加失败！" + "失败信息为:" + res.msg);
          getList();
        }
      })
      .catch((msg) => {
        ElMessage.error("添加失败,请联系管理员！");
      });
     return; 
};
const reDataValue = (data) => {
  let tempData = [];
  let list = data.JobAndTrigger.list;

  for (let index = 0; index < list.length; index++) {
    if (list[index].jobData != undefined && list[index].jobData != "") {
      tempData = list[index].jobData.split("\n")[2].split("=");
      let value = tempData[1];
      list[index].invokeParam = value;
    } else {
      list[index].invokeParam = "";
    }
  }
  return list;
};
const cronChange = (data) =>{
  let interval = cronParser.parseExpression(data)
  for(let i = 0;i<5;i++){
  }
}
/**
 * 页数据总数改变
 */
const sizeChange = (value) => {
  pagination.size = value;
  pagination.page = 1;
  getList();
};
/**
 * 页总数改变
 */
const pageChange = (value) => {
  pagination.page = value;
  getList();
};
const changeCron = (val) => {
  if (typeof val !== "string") return false;
  formData.logicConfig = val;
};

getList();
</script>

<style lang="less" scoped>
.title {
  min-width: 5em;
}
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
.el-card__header {
  max-height: 10vh;
}
.pagination {
  max-height: 3vh;
}
</style>
